/*
 * Copyright (C) 2015 备胎金服
 * 未经授权允许不得进行拷贝和修改
 *   http://www.btjf.com/
 */
package com.zhangman.framework.implementation;

import android.view.MotionEvent;
import android.view.View;
import com.zhangman.framework.Input;
import com.zhangman.framework.Pool;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhangman on 2016/11/1 13:37.
 * Email: zhangman523@126.com
 */
public class SingleTouchHandler implements TouchHandler {
  boolean isTouched;
  int touchX;
  int touchY;
  Pool<Input.TouchEvent> touchEventPool;
  List<Input.TouchEvent> touchEvents = new ArrayList<>();
  List<Input.TouchEvent> touchEventsBuffer = new ArrayList<>();
  float scaleX;
  float scaleY;

  public SingleTouchHandler(View view, float scaleX, float scaleY) {
    Pool.PoolObjectFactory<Input.TouchEvent> factory =
        new Pool.PoolObjectFactory<Input.TouchEvent>() {
          @Override public Input.TouchEvent createObject() {
            return new Input.TouchEvent();
          }
        };
    touchEventPool = new Pool<Input.TouchEvent>(100, factory);
    view.setOnTouchListener(this);
    this.scaleX = scaleX;
    this.scaleY = scaleY;
  }

  @Override public boolean isTouchDown(int pointer) {
    synchronized (this) {
      if (pointer == 0) {
        return isTouched;
      } else {
        return false;
      }
    }
  }

  @Override public int getTouchX(int pointer) {
    synchronized (this) {
      return touchX;
    }
  }

  @Override public int getTouchY(int pointer) {
    synchronized (this) {
      return touchY;
    }
  }

  @Override public List<Input.TouchEvent> getTouchEvents() {
    synchronized (this) {
      int len = touchEvents.size();
      for (int i = 0; i < len; i++) {
        touchEventPool.free(touchEvents.get(i));
      }
      touchEvents.clear();
      touchEvents.addAll(touchEventsBuffer);
      touchEventsBuffer.clear();
      return touchEvents;
    }
  }

  @Override public boolean onTouch(View view, MotionEvent motionEvent) {
    synchronized (this) {
      Input.TouchEvent touchEvent = touchEventPool.newObject();
      switch (motionEvent.getAction()) {
        case MotionEvent.ACTION_DOWN:
          touchEvent.type = Input.TouchEvent.TOUCH_DOWN;
          isTouched = true;
          break;
        case MotionEvent.ACTION_MOVE:
          touchEvent.type = Input.TouchEvent.TOUCH_DRAGGED;
          isTouched = true;
          break;
        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:
          touchEvent.type = Input.TouchEvent.TOUCH_UP;
          isTouched = false;
          break;
      }
      touchEvent.x = touchX = (int) (motionEvent.getX() * scaleX);
      touchEvent.y = touchY = (int) (motionEvent.getY() * scaleY);
      touchEventsBuffer.add(touchEvent);
      return true;
    }
  }
}
